package lockDemo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Ajie
 * @date 8/10/21
 * @function
 * lock.tryLock(）中断测试
 */
public class LockInterruptDemo {
    //实例化Lock对象
    static Lock lock = new ReentrantLock();

    /**
     * @param args
     */
    public static void main(String[] args) {
        //实例化本类对象，目的是调用runThread方法
        LockInterruptDemo tl = new LockInterruptDemo();
        //匿名对象创建线程1，并重写run方法，启动线程
        Thread thread = new Thread(() -> {

                try {
                    System.out.println("线程" + Thread.currentThread().getName() + " wait 锁");
                    lock.lock();
                    System.out.println("线程" + Thread.currentThread().getName() + "获取 锁");
                    while (true){

                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                    System.out.println("线程" + Thread.currentThread().getName() + "释放锁");
                }

                },"thread origin");
        thread.start();

        Thread thread2 = new Thread(() -> {

            try {
                System.out.println("线程" + Thread.currentThread().getName() + " wait 锁");
                lock.lock();
                System.out.println("线程" + Thread.currentThread().getName() + "获取 锁");
                while (true){

                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
                System.out.println("线程" + Thread.currentThread().getName() + "释放锁");
            }

        },"thread 2");
        thread2.start();

        new Thread(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("thread2.interrupt()");
                lock.lockInterruptibly();
                thread2.interrupt();
//                    tl.lock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"thrad 3").start();


    }

}
